package com.heima.wemedia.service.impl;
import java.util.Date;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.wemedia.utils.WmThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Objects;
import java.util.UUID;

/**
 * @author Shizhicong
 */
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    private FileStorageService fileStorageService;

    @Override
    public ResponseResult uploadPicture(MultipartFile file) {
        //1.检查参数
        if(file==null||file.isEmpty()){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.处理业务
        //2.1 文件重命名
        String filename = file.getOriginalFilename();
        assert filename != null;
        String suffix = filename.substring(filename.lastIndexOf("."));
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        filename = uuid.concat(suffix);
        //2.2 文件上传
        String path = "";
        try {
            path = fileStorageService.uploadImgFile("", filename, file.getInputStream());
        } catch (IOException e) {
            throw new CustomException(AppHttpCodeEnum.FILE_UPLOAD_ERROR);
        }
        //2.3 保存图片信息到数据库中
        Integer userId = WmThreadLocalUtil.getWmUserId();
        if (Objects.isNull(userId)){
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(userId);
        wmMaterial.setUrl(path);
        wmMaterial.setType((short)0);
        wmMaterial.setIsCollection((short)0);
        wmMaterial.setCreatedTime(new Date());
        save(wmMaterial);
        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public ResponseResult listMaterial(WmMaterialDto dto) {
        //检查参数
        if (Objects.isNull(dto)){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        Integer userId = WmThreadLocalUtil.getWmUserId();
        if (Objects.isNull(userId)){
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        //处理业务
        Page<WmMaterial> page = new Page<>(dto.getPage(),dto.getSize());
        lambdaQuery().eq(WmMaterial::getUserId,userId)
                .eq(Objects.nonNull(dto.getIsCollection()),WmMaterial::getIsCollection,dto.getIsCollection())
                .orderByDesc(WmMaterial::getCreatedTime)
                .page(page);
        PageResponseResult result = new PageResponseResult(dto.getPage(),dto.getSize(),(int)page.getTotal());
        result.setData(page.getRecords());
        return result;
    }

    /**
     * 收藏素材
     * @param id
     * @return
     */
    @Override
    public ResponseResult collectMaterial(Integer id) {
        lambdaUpdate().eq(WmMaterial::getId,id).set(WmMaterial::getIsCollection,1).update();
        WmMaterial material = getById(id);
        return ResponseResult.okResult(material);
    }

    /**
     * 取消收藏素材
     * @param id
     * @return
     */
    @Override
    public ResponseResult cancelCollect(Integer id) {
        lambdaUpdate().eq(WmMaterial::getId,id).set(WmMaterial::getIsCollection,0).update();
        WmMaterial material = getById(id);
        return ResponseResult.okResult(material);
    }

    /**
     * 删除素材
     * @param id
     * @return
     */
    @Override
    public ResponseResult delPicture(Integer id) {
        removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
